package net.sync.lesson1;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author ${user}
 * @version V1.0
 * @Title: ${file_name}
 * @Package ${package_name}
 * @Description: ${todo}(用一句话描述该文件做什么)
 * @date ${date}
 */
public class ThreadDemo {
    private int sharedState;

    public void nonShareAction(){
        while (sharedState<10000) {
//            int former = sharedState++;
//            int latter = sharedState;
            synchronized (this){
                int former = sharedState++;
                int latter = sharedState;
                if (former != latter - 1) {
                    System.out.println("former :" + former + ", latter:" + latter);
                }
            }
        }
    }

    public void nonShareAction1(){
        ReentrantLock rl = new  ReentrantLock(true);
        while (sharedState<10000) {
//            int former = sharedState++;
//            int latter = sharedState;
            try {
                rl.lockInterruptibly();
                int former = sharedState++;
                int latter = sharedState;
                if (former != latter - 1) {
                    System.out.println("former :" + former + ", latter:" + latter);
                }
            } catch (InterruptedException e) {

            }finally {
                rl.unlock();
            }
        }
    }

    public static void main(String[] args) {
        ThreadDemo th = new ThreadDemo();
        Thread t =new Thread( ()->{
            th.nonShareAction1();
        });

        Thread t1 =new Thread( ()->{
            th.nonShareAction1();
        });
        t.start();
        t1.start();
        try {
            t.join();
            t1.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
